package com.tengits.upgrade;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.text.TextUtils;
import android.widget.Toast;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import java.io.File;

import com.facebook.react.bridge.ActivityEventListener;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.LifecycleEventListener;
import com.facebook.react.bridge.BaseActivityEventListener;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.UiThreadUtil;
import com.facebook.react.modules.core.PermissionListener;
import com.facebook.react.modules.core.PermissionAwareActivity;

public class UpgradeLibraryModule extends ReactContextBaseJavaModule implements LifecycleEventListener, PermissionListener{

    private static final String TAG = UpgradeLibraryModule.class.getSimpleName();
    private static final int MY_PERMISSIONS_REQUEST_WRITE_STORAGE = 1002;

    private final ReactApplicationContext reactContext;
    private BroadcastReceiver mBroadcastReceiver;
    private LocalBroadcastManager mBroadcastManager;
    private String installPath;
    private Promise promise;

    private int isForce;
    private String versionUrl;
    private String versionName;
    private String versionDesc;

    private final ActivityEventListener mActivityEventListener = new BaseActivityEventListener() {

        @Override
        public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
            if (resultCode == Activity.RESULT_OK && requestCode == InstallUtils.UNKNOWN_CODE && !TextUtils.isEmpty(installPath)) {
                Log.e("upgrade", "onActivityResult");
                File testFile = new File(installPath);
                if(testFile.exists()) {
                    InstallUtils.install(getCurrentActivity(), installPath);
                }
            }
        }
      };

    public UpgradeLibraryModule(ReactApplicationContext reactContext) {
        super(reactContext);
        this.reactContext = reactContext;
        this.reactContext.addLifecycleEventListener(this);
        this.reactContext.addActivityEventListener(mActivityEventListener);
        mBroadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, final Intent intent) { // 所有任务完成后，都会发广播过来
                if ("download_apk_broadcast".equals(intent.getAction())) { // 需要同步数据
                installPath = intent.getStringExtra("path");
                InstallUtils.install(getCurrentActivity(), installPath);
                }
            }
        };

        IntentFilter filter = new IntentFilter();
        filter.addAction("download_apk_broadcast");
        try{
            mBroadcastManager = LocalBroadcastManager.getInstance(reactContext);
            mBroadcastManager.registerReceiver(mBroadcastReceiver, filter);
        }catch(Exception e) {
            Log.e("UpgradeLibraryModule", e.getMessage());
        }
    }

    @Override
    public String getName() {
        return "UpgradeLibrary";
    }

    @ReactMethod
    public void doNewVersionUpdate(final int isForce, final String versionUrl,
                                   final String versionName,
                                   String versionDesc,
                                   final Promise promise) {
        this.isForce = isForce;
        this.versionUrl = versionUrl;
        this.versionName = versionName;
        this.versionDesc = versionDesc;
        this.promise = promise;
        final PermissionAwareActivity activity = (PermissionAwareActivity) getCurrentActivity();
        if (activity.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                                    != PackageManager.PERMISSION_GRANTED) {
            if (activity.shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                Log.e(TAG,"shouldShowRequestPermissionRationale");

                activity.requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_WRITE_STORAGE, this);

            } else {
                Log.e(TAG,"requestPermissions");
                // No explanation needed, we can request the permission.
                activity.requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_WRITE_STORAGE, this);
            }
        } else {
            showUpdateDialog(getCurrentActivity(), isForce, versionUrl, versionName, versionDesc, promise);
        }
    }

    @ReactMethod
    public void showWatermarkView(final String text) {
        UiThreadUtil.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                final Activity currentActivity = getCurrentActivity();
                WaterMarkUtils.showWatermarkView(currentActivity, text);
            }
        });
    }

    @ReactMethod
    public void openSettingsActivity(Callback cb) {
        Activity currentActivity = getCurrentActivity();

        if (currentActivity == null) {
            cb.invoke(false);
            return;
        }
        try {
            Intent localIntent = new Intent();
            localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            if (Build.VERSION.SDK_INT >= 9) {
                localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                localIntent.setData(Uri.fromParts("package", currentActivity.getPackageName(), null));
            } else if (Build.VERSION.SDK_INT <= 8) {
                localIntent.setAction(Intent.ACTION_VIEW);
                localIntent.setClassName("com.android.settings", "com.android.setting.InstalledAppDetails");
                localIntent.putExtra("com.android.settings.ApplicationPkgName", currentActivity.getPackageName());
            }

            currentActivity.startActivity(localIntent);

            //currentActivity.startActivity(new Intent(android.provider.Settings.ACTION_SETTINGS));
            cb.invoke(true);
        } catch (Exception e) {
            cb.invoke(e.getMessage());
        }
    }

    private static void showUpdateDialog(final Activity activity,
                                         final int isForce,
                                         final String versionUrl,
                                         final String versionName,
                                         String versionDesc,
                                         final Promise promise) {
        UIDialog.showUpdateDialog(activity, isForce, "有新版本啦", versionName, versionDesc, "立即更新", "稍后", new UIDialog.PositiveButtonClickListener() {
            @Override
            public void setPositiveButton(DialogInterface dialog, int which) {
                if(checkInstallPermission(activity)) {
                    if (Utils.isOnline(activity)) {
                        //EasySharedPreference.setSharedBooleanData(PrefsConst.CANCEL_UPDATE + versionName, true);
                        promise.resolve("positive");
                        new VersionUpdateAsyncTask(activity)
                                .execute(new String[]{versionUrl,
                                        versionName});
                    } else {
                        Toast.makeText(activity, "网络出错,请稍后再试", Toast.LENGTH_LONG).show();
                    }
                } else {
                    Uri packageURI = Uri.parse("package:" + activity.getPackageName());
                    Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
                    activity.startActivity(intent);
                }
            }
        }, new UIDialog.NegativeButtonClickListener() {
            @Override
            public void setNegativeButton(DialogInterface dialog) {
                //EasySharedPreference.setSharedBooleanData(PrefsConst.CANCEL_UPDATE + versionName, true);
                promise.resolve("negative");
            }
        });
    }

    private static boolean checkInstallPermission(Context context) {
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            return context.getPackageManager().canRequestPackageInstalls();
        }
        return true;
    }

    @Override
    public void onHostResume() {
        // Activity `onResume`
    }

    @Override
    public void onHostPause() {
        // Activity `onPause`
    }

    @Override
    public void onHostDestroy() {
        // Activity `onDestroy`
        mBroadcastManager.unregisterReceiver(mBroadcastReceiver);
        reactContext.removeLifecycleEventListener(this);
        reactContext.removeActivityEventListener(mActivityEventListener);
    }

    @Override
    public boolean onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_WRITE_STORAGE: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Log.e(TAG,"onRequestPermissionsResult granted");
                    showUpdateDialog(getCurrentActivity(), this.isForce, this.versionUrl, this.versionName, this.versionDesc, this.promise);
                } else {
                    Log.e(TAG,"onRequestPermissionsResult denied");
                    UpgradeLibraryModule.this.promise.resolve("negative");
                    showWaringDialog();
                }
                return false;
            }
        }
        return true;
    }

    private void showWaringDialog() {
        Log.e(TAG, "showWaringDialog");
        AlertDialog dialog = new AlertDialog.Builder(getCurrentActivity())
                .setTitle("警告！")
                .setMessage("请前往设置->应用->PermissionDemo->权限中打开相关权限，否则功能无法正常运行！")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 一般情况下如果用户不授权的话，功能是无法运行的，做退出处理
                        Intent intent = new Intent();
                        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                        intent.setData(Uri.fromParts("package", UpgradeLibraryModule.this.reactContext.getPackageName(), null));
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        UpgradeLibraryModule.this.reactContext.startActivity(intent);
                    }
                }).show();
    }
}
